package org.lex.ftp.ui.queue;

import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.lex.ftp.FTP;
import org.lex.ftp.queue.QueueHandler;
import org.lex.ftp.queue.Task;
import org.lex.ftp.queue.TransferQueue;

public class QueuePane extends JTable {
	private final FTP app;
	private TransferQueue queue = null;
	private QueueHandler queueHandler = null;

	public QueuePane(FTP app) {
		super();
		this.app = app;
		this.initialize();
	}

	public void transfer() {
		this.getQueueHandler().transfer();
	}

	public void abort() {
		this.getQueueHandler().abort();
	}

	public Task[] getSelectedTasks() {
		int[] rows = this.getSelectedRows();
		Task[] tasks = new Task[rows.length];
		for (int i = 0; i < rows.length; i++)
			tasks[i] = this.getTask(rows[i]);
		return tasks;
	}

	public int getSelectedModelRow() {
		int row = this.getSelectedRow();
		if (-1 == row)
			return -1;
		else
			return this.convertRowIndexToModel(row);
	}

	public int[] getSelectedModelRows() {
		int[] rows = this.getSelectedRows();
		for (int i = 0; i < rows.length; i++)
			rows[i] = this.convertRowIndexToModel(rows[i]);
		return rows;
	}

	public Task getSelectedTask() {
		return this.getTask(getSelectedRow());
	}

	public Task getTask(int viewRowIndex) {
		if (-1 == viewRowIndex)
			return null;
		int modelRowIndex = this.convertRowIndexToModel(viewRowIndex);
		return this.getQueue().getTask(modelRowIndex);
	}

	public TransferQueue getModel() {
		if (null == queue)
			this.queue = new TransferQueue();
		return this.queue;
	}

	public TransferQueue getQueue() {
		return this.getModel();
	}

	private QueueHandler getQueueHandler() {
		if (null == queueHandler)
			queueHandler = new QueueHandler(app.getFTPExplorer());
		return queueHandler;
	}

	// =======================
	private void initialize() {
		this.setModel(this.getModel());
		this.setFillsViewportHeight(true);
		this.setName(this.getClass().getName() + ".table");
		this.setShowGrid(false);
		this.setComponentPopupMenu(new QueuePopupMenu(app));
		// width & renderer
		this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		TableColumn column = null;
		TableColumnModel model = this.getColumnModel();
		TableCellRenderer[] renderers = { SourceRenderer.getInstance(), null, SizeRenderer.getInstance(), null };
		int[] width = COLUMN_WIDTHS;
		for (int i = 0; i < width.length; i++) {
			column = model.getColumn(i);
			column.setPreferredWidth(width[i]);
			if (null != renderers[i])
				column.setCellRenderer(renderers[i]);
		}
	}

	private static final int[] COLUMN_WIDTHS = { 275, 350, 50, 225 };
}
